<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="批次ID" prop="qrPatchID">
        <el-input
          v-model="queryParams.qrPatchID"
          placeholder="请输入批次ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="零售商" prop="qrRetailerInfo">
        <el-input
          v-model="queryParams.qrRetailerInfo"
          placeholder="请输入零售商信息"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['seedlingSys:qr:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchAdd"
          v-hasPermi="['seedlingSys:qr:add']"
          >批量新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['seedlingSys:qr:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="qrList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="二维码ID" align="center" prop="qrID" />
      <el-table-column label="批次ID" align="center" prop="qrPatchID" />
      <el-table-column
        label="生成时间"
        align="center"
        prop="qrProductionTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.qrProductionTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="唯一编码" align="center" prop="qrUniqueCode" />
      <el-table-column
        label="零售商信息"
        align="center"
        prop="qrRetailerInfo"
      />
      <el-table-column label="二维码" align="center" width="180">
        <template slot-scope="scope">
          <qrcode-vue
            :value="getQrContent(scope.row)"
            :size="100"
            level="H"
          ></qrcode-vue>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['seedlingSys:qr:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联批次" prop="qrPatchID">
          <el-select v-model="form.qrPatchID" placeholder="请选择批次">
            <el-option
              v-for="item in patchOptions"
              :key="item.patchID"
              :label="item.patchName"
              :value="item.patchID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="零售商" prop="qrRetailerInfo">
          <el-input
            v-model="form.qrRetailerInfo"
            placeholder="请输入零售商信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量添加对话框 -->
    <el-dialog
      title="批量新增二维码"
      :visible.sync="batchOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="batchForm"
        :model="batchForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="关联批次" prop="qrPatchID">
          <el-select v-model="batchForm.qrPatchID" placeholder="请选择批次">
            <el-option
              v-for="item in patchOptions"
              :key="item.patchID"
              :label="item.patchName"
              :value="item.patchID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="零售商" prop="qrRetailerInfo">
          <el-input
            v-model="batchForm.qrRetailerInfo"
            placeholder="请输入零售商信息"
          />
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input-number v-model="batchForm.count" :min="1" :max="100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchForm">确 定</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQr, getQr, delQr, addQr, batchAddQr } from "@/api/seedlingSys/qr";
import { listPatch } from "@/api/seedlingSys/patch";
import QrcodeVue from "qrcode.vue";
import { v4 as uuidv4 } from "uuid";

export default {
  name: "Qr",
  components: {
    QrcodeVue,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 二维码表格数据
      qrList: [],
      // 批次选项
      patchOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示批量添加弹出层
      batchOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qrPatchID: null,
        qrRetailerInfo: null,
      },
      // 表单参数
      form: {},
      // 批量表单参数
      batchForm: {
        qrPatchID: null,
        qrRetailerInfo: "",
        count: 1,
      },
      // 表单校验
      rules: {
        qrPatchID: [
          { required: true, message: "批次不能为空", trigger: "change" },
        ],
        qrRetailerInfo: [
          { required: true, message: "零售商信息不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getPatchOptions();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listQr(this.queryParams).then((response) => {
        this.qrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取批次选项 */
    getPatchOptions() {
      listPatch().then((response) => {
        this.patchOptions = response.rows;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 取消批量添加 */
    cancelBatch() {
      this.batchOpen = false;
      this.batchForm = {
        qrPatchID: null,
        qrRetailerInfo: "",
        count: 1,
      };
    },
    /** 表单重置 */
    reset() {
      this.form = {
        qrPatchID: null,
        qrRetailerInfo: null,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.qrID);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加二维码";
    },
    /** 批量新增按钮操作 */
    handleBatchAdd() {
      this.batchOpen = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const qrIds = row.qrID || this.ids;
      this.$modal
        .confirm('是否确认删除二维码编号为"' + qrIds + '"的数据项？')
        .then(function () {
          return delQr(qrIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.qrUniqueCode = uuidv4();
          this.form.qrProductionTime = new Date();
          addQr(this.form).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 批量提交按钮 */
    submitBatchForm() {
      this.$refs["batchForm"].validate((valid) => {
        if (valid) {
          const qrs = [];
          for (let i = 0; i < this.batchForm.count; i++) {
            qrs.push({
              qrPatchID: this.batchForm.qrPatchID,
              qrRetailerInfo: this.batchForm.qrRetailerInfo,
              qrUniqueCode: uuidv4(),
              qrProductionTime: new Date(),
            });
          }
          batchAddQr(qrs).then((response) => {
            this.$modal.msgSuccess("批量新增成功");
            this.batchOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 生成二维码内容 */
    getQrContent(row) {
      const baseUrl = window.location.origin;
      // 使用正确的API路径
      return `${baseUrl}/PatchView?code=${row.qrUniqueCode}`;
    },
  },
};
</script>
